#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

#define FILEPATH "../../data/zipf_1000000_1.75.bin"
//#define NUMINTS  262144

using namespace std;

void do_mmap() {
	struct stat sb;
	//printf("Staring filesize: %f\n ", FILESIZE);
	int fd = open(FILEPATH, O_RDONLY);
	StreamSummaryBuffer hs(800,800);
	int * iptr;
	float * fptr;
	int FILESIZE;

	if (fd == -1) {
		perror("Error opening file for reading");
		exit (EXIT_FAILURE);
	}

	if (fstat(fd, &sb) == -1) {
			perror("Error on fstat");
			exit(EXIT_FAILURE);
		}

	FILESIZE = sb.st_size / (sizeof(int) + sizeof(float));
	char * map = (char *) mmap(0, sb.st_size, PROT_READ, MAP_SHARED, fd, 0);
	if (map == MAP_FAILED) {
		close(fd);
		perror("Error mmapping the file");
		exit (EXIT_FAILURE);
	}
	iptr = (int*) map;
	for (int i = 0; i < 2; i++) {
		fptr = (float*) (iptr + 1);
		//cerr <<  iptr[0] << "," << fptr[0] << endl;
		hs.insert(iptr[0], iptr[0], fptr[0]);
		iptr = (int*) (iptr + 2);
	}

	if (munmap(map, sb.st_size) == -1) {
		perror("Error un-mmapping the file");
	}

	close(fd);
	printf("finished\n ");
}

int main(int argc, char *argv[]) {
	do_mmap();

return 0;
}
